import cloneDeep from "lodash/cloneDeep.js"
import {renderIcon} from "@/config/icon"
import isArray from "lodash/isArray"

const removeElements = (tree: any): void => {
    for (let i = tree.length - 1; i >= 0; i--) {
        const node = tree[i]
        if (node.level >= 3) {
            tree.splice(i, 1) // 从父节点的 children 数组中移除当前节点
        } else if (node.children) {
            removeElements(node.children) // 递归处理子节点
            if (node.children.length === 0) {
                delete node.children // 如果子节点为空数组，则删除 children 字段
            }
        }
    }
}

const reBuildIcon = (allMenus: any) => {
    const data: any = []
    allMenus.forEach((item: any) => {
        if (item.icon) {
            item.icon = renderIcon(item.icon)
        } else {
            delete item.icon
        }
        if (isArray(item.children)) {
            item.children = reBuildIcon(item.children)
        }
        data.push(item)
    })

    return data
}

/**
 * 生成链路
 * @param arr
 * @param id
 */
const getObjectPath = ({arr = <any>[], id = ""}) => {
    const data = cloneDeep(arr)
    for (const i in arr) {
        // eslint-disable-next-line no-prototype-builtins
        if (data.hasOwnProperty(i)) {
            if (arr[i].id === id) {
                return [data[i]]
            }
            if (data[i].children) {
                const node: any = getObjectPath({arr: data[i].children, id})
                if (node !== undefined) {
                    return node.concat(data[i])
                }
            }
        }
    }
}


function htmlElementClass(state: boolean, clsName: string, target?: HTMLElement) {
    const targetEl = target || document.body
    if (state) {
        targetEl.classList.add(clsName)
    } else {
        targetEl.classList.remove(clsName)
    }
}


export {
    removeElements,
    getObjectPath,
    htmlElementClass,
    reBuildIcon
}
